#include "stm32f10x.h"                  // Device header
#include "stdio.h"

uint8_t rxdata;
uint8_t rxdata_flag;

void serial_init(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
	
	GPIO_InitTypeDef serial_gpio_init;
	serial_gpio_init.GPIO_Mode=GPIO_Mode_AF_PP;
	serial_gpio_init.GPIO_Pin=GPIO_Pin_9;
	serial_gpio_init.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&serial_gpio_init);
	
	serial_gpio_init.GPIO_Mode=GPIO_Mode_IPU;
	serial_gpio_init.GPIO_Pin=GPIO_Pin_10;
	GPIO_Init(GPIOA,&serial_gpio_init);
	
	USART_InitTypeDef serial_usart_init;
	serial_usart_init.USART_BaudRate=9600;
	serial_usart_init.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
	serial_usart_init.USART_Mode=USART_Mode_Tx|USART_Mode_Rx;
	serial_usart_init.USART_Parity=USART_Parity_No;
	serial_usart_init.USART_StopBits=USART_StopBits_1;
	serial_usart_init.USART_WordLength=USART_WordLength_8b;
	USART_Init(USART1,&serial_usart_init);
	
	USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);
	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	NVIC_InitTypeDef serial_nvic_init;
	serial_nvic_init.NVIC_IRQChannel=USART1_IRQn;
	serial_nvic_init.NVIC_IRQChannelCmd=ENABLE;
	serial_nvic_init.NVIC_IRQChannelPreemptionPriority=1;
	serial_nvic_init.NVIC_IRQChannelSubPriority=1;
	NVIC_Init(&serial_nvic_init);
	

	USART_Cmd(USART1,ENABLE);
}

void serial_sendbyte(uint8_t a)
{
	USART_SendData(USART1,a);
	while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==RESET);
}

void serial_sendstring(char *str)
{
	while(*str)
	{
		serial_sendbyte(*str++);
	}
}

int fputc(int ch,FILE *f)
{
	serial_sendbyte(ch);
	return ch;
}

void USART1_IRQHandler(void)
{
	if(USART_GetITStatus(USART1,USART_IT_RXNE)==SET)
	{
		rxdata=USART_ReceiveData(USART1);
		rxdata_flag=1;
		USART_ClearITPendingBit(USART1,USART_IT_RXNE);
	}
}
